# coding=utf-8
# 全世界最帅的帅哥
from flask import g, request, current_app
from flask_restful import Resource, reqparse
from sqlalchemy.exc import SQLAlchemyError

from ysgg1_club_comment.es_fields.es_subject_fields import EsSubjectFields
from ysgg1_club_comment.utils.id_worker_util import IdWorkerUtil
from ysgg1_club_subject.constant.redis_prefix import RedisPrefix
from ysgg1_club_subject.handler.subject.subject_type_handler_factory import SubjectTypeHandlerFactory
from ysgg1_club_subject.redis_client import redis_liked_client
from ysgg1_club_subject.subject_views.subject_views import query_subject_list, query_subject_by_es, \
    get_contribute_list, query_subject_info


class SubjectResource(Resource):
    def get(self, action=None):
        if action == "queryList":
            return query_subject_list()
        elif action == "querySubjectList":
            return query_subject_by_es()
        elif action == "querySubjectInfo":
            return query_subject_info()

        elif action:
            return {"code": 500, "success": False, "message": "输入错误的网址啦"}

    def post(self, action=None):
        try:
            if action == "insert":
                parser = reqparse.RequestParser()
                parser.add_argument('subjectType', required=True, help="题目分类不能为空")
                args = parser.parse_args()
                subject_type = int(args.subjectType)
                # 通过题目类型调用对应的handler
                handler = SubjectTypeHandlerFactory.get_handler(subject_type)
                # 新增对应的题目
                es_dict = handler.add()
                if es_dict.get("code") == 500:
                    return {"code": 500, "success": False, "message": "failed"}
                doc_id = IdWorkerUtil(1, 1).next_id()
                doc = EsSubjectFields(
                    doc_id=doc_id, **es_dict
                )
                doc.save()
                redis_liked_client.zadd(RedisPrefix.RANK_KEY, g.token, 1)
                current_app.logger.info(f"新增点赞成功, 点赞人{g.token}, 点赞题目{}")
                return {"code": 200, "msg": "success"}

            elif action == "getContributeList":
                return get_contribute_list()
        except (Exception, SQLAlchemyError) as e:
            return {"code": 500, "success": False, "message": "服务器错误."}